package com.anzhen.interview.juc;

import org.junit.Test;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * Created by zhenan on 2017-3-21.
 */
public class CyclicBarrierTest {

    @Test
    public void test01() throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(1);
            }
        }).start();
        System.out.println("3");
    }

    @Test
    public void test02() throws InterruptedException, BrokenBarrierException {
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(1000);
        for (int i = 0; i < 1000; i++) {
            final int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(finalI);
                    try {
                        cyclicBarrier.await();
                    } catch (InterruptedException | BrokenBarrierException e) {
                        e.printStackTrace();
                    }
                    System.out.println("当前剩余 " + cyclicBarrier.getNumberWaiting());
                }
            }).start();
        }
        cyclicBarrier.await();
        System.out.println("完事");
    }
}
